package com.yntx.usercenter.common.util;

import java.util.UUID;

/**
 * Description: 生成随机唯一字符串
 * 使用UUID，UUID是128位值，getMostSignificantBits() 获取uuid最高有效64位
 * <p>
 * UUID                                 ->      d18df239-5998-4d92-8bb6-42f5f52b991d
 * UUID.getMostSignificantBits()        ->      3346752619936199278
 * UUID.getLeastSignificantBits()       ->      8379436432528533219
 *
 * @author Liziba
 * @version 1.0
 * @date 2022/9/29 11:13 AM
 * @since JDK 1.8
 */
public class GUID {

    /**
     * 获取一个26位的随机唯一字符串
     *
     * @return
     */
    public static String get() {
        UUID uuid = UUID.randomUUID();
        StringBuffer sb = new StringBuffer();
        get(sb, uuid.getMostSignificantBits());
        get(sb, uuid.getLeastSignificantBits());
        return sb.toString();
    }

    private static StringBuffer get(StringBuffer sb, long bits) {
        int count = 13;
        while (count-- > 0) {
            long low = bits & 0x1FL;
            if (low < 10L) {
                sb.append((char) ('0' + low));
            } else {
                sb.append((char) ('A' + (low - 10)));
            }

            bits >>>= 5;
        }

        return sb;
    }

}
